I'm showing and hiding different headings depending on the device screen width. As react allows me to mount and unmount a component depending on a state I sometimes used the event listener addEventLister("resize", handleResize) to show and hide elements.
But with this method on a new page refresh, some flickering appeared as the default value of state was replaced by the actual evaluated value of the screen width, which caused the bigger typo to be shown for a millisecond before it was hidden again.
I discovered this won't happen with @media screen and display: none.
Why is it so slow? And is there any workaround for cases where I can't solve it in CSS, so a way to prioritize the event listener to evaluate before showing the wrong heading?
What's the go-to way for these scenarios, as this must be a basic issue on all responsive sites?
Example for a custom hook to listen for window changes:
const [screenSize, setScreenSize] = useState<Size>({
width: 0,
height: 0,
});
useEffect(() => {
const handleResize = () => {
setScreenSize({ width: window.innerWidth, height: window.innerHeight });
};
addEventListener("resize", handleResize);
handleResize();
return () => removeEventListener("resize", handleResize);
}, []);
Css example to do the same:
.title {
display: flex;
}
@media screen and (max-width: 768px) {
.title {
display: none;
}
}